<template>
  <el-dialog
    v-model="visible"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item label="文档标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="文档描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入文档描述"
        />
      </el-form-item>

      <el-form-item label="文档标签">
        <el-tag
          v-for="(tag, index) in form.tags"
          :key="index"
          closable
          @close="removeTag(index)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="inputRef"
          v-model="inputValue"
          size="small"
          style="width: 100px"
          @keyup.enter="addTag"
          @blur="addTag"
        />
        <el-button
          v-else
          size="small"
          @click="showInput"
        >
          + 添加标签
        </el-button>
      </el-form-item>

      <el-form-item label="访问权限">
        <el-radio-group v-model="form.accessLevel">
          <el-radio-button label="Public">
            <div class="permission-option">
              <span>对外公开</span>
            </div>
          </el-radio-button>
          <el-radio-button label="Internal">
            <div class="permission-option">
              <span>对内公开</span>
            </div>
          </el-radio-button>
        </el-radio-group>
        <div class="permission-tips">
          <span v-if="form.accessLevel === 'Internal'">仅内部用户可访问</span>
          <span v-else>所有用户均可访问</span>
        </div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitting">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch,nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { updateDocument } from '@/api/document'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  document: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(null)
const formRef = ref(null)
const submitting = ref(false)
const inputVisible = ref(false)
const inputValue = ref('')
const inputRef = ref(null)
// 表单数据
const form = ref({
  title: '',
  description: '',
  tags: [],
  accessLevel: 'Internal' // 新增权限字段
})

// 表单验证规则
const rules = ref({
  title: [
    { required: true, message: '请输入文档标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ]
})

// 标签管理方法
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const addTag = () => {
  if (inputValue.value && !form.value.tags.includes(inputValue.value)) {
    form.value.tags.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const removeTag = (index) => {
  if (Array.isArray(form.value.tags)) {
    form.value.tags.splice(index, 1)
  } else {
    // 如果不是数组，重置为空数组
    form.value.tags = []
  }
}

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    initForm()
  }
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 初始化表单
const initForm = () => {
  form.value = {
    title: props.document.title,
    description: props.document.description || '',
    tags: Array.isArray(props.document.tags) 
      ? [...props.document.tags] 
      : (props.document.tags || '').split(',').filter(tag => tag.trim()),
    accessLevel: props.document.accessLevel || 'Internal' // 从文档数据初始化
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
  
    const params = {
      title: form.value.title,
      description: form.value.description,
      tags: form.value.tags.join(','),
      accessLevel: form.value.accessLevel // 包含权限设置
    }
    console.log(params);
    console.log(props.document.id);
    
    let res =await updateDocument(props.document.id, params)
    console.log(res);
    
    ElMessage.success('更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'validate') {
      console.error('更新失败:', error)
      ElMessage.error('更新失败')
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.permission-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 10px;
}

/* 自定义el-tag深色主题样式 */
:deep(.el-tag) {
  background: linear-gradient(135deg, rgba(0, 20, 40, 0.8) 0%, rgba(0, 40, 80, 0.8) 100%) !important;
  border: 1px solid rgba(0, 212, 255, 0.3) !important;
  color: #ffffff !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
  font-weight: 500 !important;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, rgba(46, 213, 115, 0.2) 0%, rgba(46, 213, 115, 0.1) 100%) !important;
  border-color: rgba(46, 213, 115, 0.4) !important;
  color: #2ed573 !important;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, rgba(255, 165, 2, 0.2) 0%, rgba(255, 165, 2, 0.1) 100%) !important;
  border-color: rgba(255, 165, 2, 0.4) !important;
  color: #ffa502 !important;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, rgba(255, 71, 87, 0.2) 0%, rgba(255, 71, 87, 0.1) 100%) !important;
  border-color: rgba(255, 71, 87, 0.4) !important;
  color: #ff4757 !important;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.2) 0%, rgba(0, 212, 255, 0.1) 100%) !important;
  border-color: rgba(0, 212, 255, 0.4) !important;
  color: #00d4ff !important;
}
</style>